package table

import (
	"context"
	"fmt"
	form "pd/server/app/pd/form/product"
	model "pd/server/app/pd/model/product"
	"pd/server/com/db"
)

type ProductTable struct {
}

func (this *ProductTable) Create(ctx context.Context, product *model.ProductModel) (err error) {
	conn, err := db.GetPdMasterConn()
	if err != nil {
		return
	}
	q := conn.Conn.NewSession().Context(ctx)
	_, err = q.InsertOne(product)
	return
}

func (this *ProductTable) Update(ctx context.Context, product *model.ProductModel) (err error) {
	conn, err := db.GetPdMasterConn()
	if err != nil {
		return
	}
	q := conn.Conn.NewSession().Context(ctx)
	_, err = q.Where("id = ? and merchant_id = ?", product.Id, product.MerchantId).Update(product)
	return
}

func (this *ProductTable) Delete(ctx context.Context, product *model.ProductModel) (err error) {
	conn, err := db.GetPdMasterConn()
	if err != nil {
		return
	}
	q := conn.Conn.NewSession().Context(ctx)
	_, err = q.Where("id = ? and merchant_id = ?", product.Id, product.MerchantId).Delete(&model.ProductModel{})
	return
}

func (this *ProductTable) List(ctx context.Context, frm *form.ListForm) (productList []*model.ProductModel, total int64, err error) {
	conn, err := db.GetPdMasterConn()
	if err != nil {
		return
	}
	q := conn.Conn.NewSession().Context(ctx)
	q.Where("merchant_id = ?", frm.MerchantId)

	if frm.Keyword != "" {
		tmp := fmt.Sprintf("%%%s%%", frm.Keyword)
		q.Where("name like ? or brand like ?", tmp, tmp)
	}
	if frm.Category != "" {
		q.Where("category = ?", frm.Category)
	}

	if frm.Current > 0 {
		q.Limit(frm.Size, (frm.Current-1)*frm.Size)
	}
	q.Desc("id")

	total, err = q.FindAndCount(&productList)

	return
}

func (this *ProductTable) GetProductBatch(ctx context.Context, ids []int64) (products map[int64]*model.ProductModel, err error) {
	conn, err := db.GetPdMasterConn()
	if err != nil {
		return
	}
	q := conn.Conn.NewSession().Context(ctx)
	var productList []*model.ProductModel
	if err = q.In("id", ids).Select("*").Find(&productList); err != nil {
		return
	}
	products = make(map[int64]*model.ProductModel, len(productList))
	for _, p := range productList {
		products[p.Id] = p
	}
	return
}
